package com.chezai.client.server.codec;

import com.chezai.client.server.ChannelListener;
import com.chezai.client.server.util.ChannelUtil;
import com.jx.driving.protocol.terminal.channel.Channel;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 处理监管发送过来的请求
 *
 * @author wuxiaozeng
 */
public class NettyChannelHandlerAdapter extends ChannelInboundHandlerAdapter {

    private ChannelListener listener;

    public NettyChannelHandlerAdapter(ChannelListener listener) {
        super();
        this.listener = listener;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel c = makesureChannel(ctx.channel());
        listener.active(c);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel c = makesureChannel(ctx.channel());
        listener.inactive(c);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel c = makesureChannel(ctx.channel());
        listener.onReceive(c, msg);
    }

    protected Channel makesureChannel(io.netty.channel.Channel c) {
        return ChannelUtil.getChannel(c);
    }

}
